package itsm.isperp.module.controller.wechat.cp;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.utils.JsonBuilder;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.app.AppConfig;
import itsm.isperp.module.service.app.AppConfigService;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpXmlOutNewsMessage.Item;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;

/**
 * 微信企业号配置
 * 
 * 
 * @author lizx
 * @date 2014-11-4
 * @since 1.0
 * 
 */
@Controller
@RequestMapping("wechat/cp/config")
public class WechatCpConfigController {
  
  @Autowired
  WxCpService wxCpService;

	@RequestMapping(value = { "", "manage" })
	public ModelAndView manage(HttpServletRequest req) {
		ModelAndView mv = new ModelAndView("wechat/cp/config");

		AppConfigService appConfigService = ContextHolder
				.getSpringBean("appConfigService");

		List<AppConfig> list = appConfigService.findAll();
		for (AppConfig appConfig : list) {
			mv.addObject(appConfig.getItemKey(), appConfig.getItemValue());
		}

		Object mcObj = mv.getModel().get("wechatCpSubscribe");
		if (mcObj != null) {
			try {
				CollectionType ct = TypeFactory.defaultInstance()
						.constructCollectionType(List.class, Item.class);
				List<Item> newsList = JsonBuilder.buildNormalBinder().fromJson(
						mcObj.toString(), ct);
				mv.addObject("newsList", newsList);
			} catch (Exception e) {

			}
		}
		return mv;
	}
	
	@RequestMapping("resetAccessToken")
  @ResponseBody
  public ResultMessage resetAccessToken() {
    String t = null;
    try {
      t = wxCpService.getAccessToken(true);
    } catch (WxErrorException e) {
      return ResultMessage.failure(e.getMessage());
    }

    return ResultMessage.success(t);
  }
}


